import store from '../store'
import { mergeQueryString, getEnv } from './index'

const verbs = {
  GET (url, params, options) {
    return fetch(params ? mergeQueryString(url, params) : url, {
      credentials: 'same-origin',
      headers: {
        'delayJsessionid': store.state.token,
      },
      ...options,
    })
  },

  POST (url, params, options) {
    return fetch(url, {
      method: 'POST',
      credentials: 'same-origin',
      headers: {
        'Content-Type': 'application/json',
        'Accept': 'application/json',
        'delayJsessionid': store.state.token,
      },
      body: JSON.stringify(params),
      ...options,
    })
  }
}

function getUrl(url) {
  if (getEnv() === 'prod') {
    return `https://tuoyanapp.com${url}`
  }
  return url
}

export default (url, method = 'GET', params = {}, options = {}) => {
  params.delayJsessionId = store.state.token
  return new Promise((resolve, reject) => {
    verbs[method](getUrl(url), params, options)
      .then(res => {
        res.json().then(data => {
          const state = data.state
          if (1 * state === 301) {
            enddelay_token.postMessage('')
            // TODO 会话续期是否可以让用户无感知，即在返回新的token后，重新调用接口？
            reject({
              reload: true
            })
          }
          resolve(data)
        })
      }).catch(e => reject(e))
  })
}